package my.tutorial.javacore.test.analytic;

/**
 * Java Test 5 Threads
 */
class HorizontalThread implements Runnable {
	private final int LEFT = 0;
	private final int RIGHT = 1;
	private Robot robot;

	public HorizontalThread(Robot robot) {
		this.robot = robot;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (robot) {
				int decision = (int) Math.round(Math.random());
				switch (decision) {
				case LEFT:
					robot.moveLeft();
					break;
				case RIGHT:
					robot.moveRight();
					break;
				}
			}
		}
	}
}

class VerticalThread implements Runnable {
	private final int FORWARD = 0;
	private final int BACKWARD = 1;
	private Robot robot;

	public VerticalThread(Robot robot) {
		this.robot = robot;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (robot) {
				int decision = (int) Math.round(Math.random());
				switch (decision) {
				case FORWARD:
					robot.moveForward();
					break;
				case BACKWARD:
					robot.moveBackward();
					break;
				}
			}
		}
	}
}

public class Robot {
	public static void main(String[] args) {
		Robot robot = new Robot();
		new Thread(new HorizontalThread(robot)).start();
		new Thread(new VerticalThread(robot)).start();
	}

	public void moveLeft() {
		System.out.println("robot moves left!");
		moving();
	}

	public void moveRight() {
		System.out.println("robot moves right!");
		moving();
	}

	public void moveForward() {
		System.out.println("robot moves forward!");
		moving();
	}

	public void moveBackward() {
		System.out.println("robot moves backward!");
		moving();
	}

	public void moving() {
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
